package com.yxy.controller.app;


import com.yxy.controller.service.AdminController;
import com.yxy.dto.UserModel;
import com.yxy.common.Const;
import com.yxy.common.ServerResponse;
import com.yxy.entity.User;
import com.yxy.service.IFileService;
import com.yxy.service.IUserService;

import com.yxy.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * 用户接口
 *
 * @author DengWenJun
 * @cerateTime 2017-08-01-9:46
 **/
@Controller
@RequestMapping("/app/user/")
public class UserController {

    public Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IFileService fileService;
    /**
     * 用户登录
     *
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<UserModel> login(@RequestBody User entity, HttpSession session, HttpServletRequest request) {

        //效验手机号是否注册
        int  resultCount = iUserService.checkPhone(entity.getPhone());
        if(resultCount==0){
            return  ServerResponse.createByErrorMessage("手机号未注册");
        }
        String md5password = MD5Util.MD5EncodeUtf8(entity.getPassword());
        User user = iUserService.login(entity.getPhone(),md5password);
        if(user == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        if(user.getStatus()!=null && user.getStatus() ==Const.Status.STATUS_FROZEN){
            return ServerResponse.createByErrorMessage("该手机号已被冻结");
        }
        user.setLoginIp(getIpAddress(request));
        iUserService.updateByPrimaryKey(user);
        UserModel userModel = new AdminController().entityToModel(user);
        userModel.setPassword(null);//置空密码

        return ServerResponse.createBySuccess("登陆成功",userModel);
    }
    //用户注册
    @RequestMapping(value = "register.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(@RequestBody UserModel model,HttpServletRequest request){

        if(model.getPassword()!=null && !model.getConfirmPassword().equals(model.getPassword())){
            return ServerResponse.createByErrorMessage("两次密码不一致");
        }
        boolean validPhone = iUserService.checkValid(model.getPhone(),"phone");
        if(validPhone){
            return ServerResponse.createByErrorMessage("手机号已被注册");
        }
        //邮箱验证
        if(model.getEmail()!=null){
            boolean validEmail = iUserService.checkValid(model.getEmail(),"email");
            if(validEmail){
                return ServerResponse.createByErrorMessage("邮箱已被注册");
            }
        }

        User user =new AdminController(). modelToEntity(model);
        user.setStatus(Const.Status.STATUS_ACTIVATION);
        user.setRole(Const.Role.ROLE_CUSTOMER);
        user.setSex(Const.Sex.SEX_MALE);
        user.setDelFlag(0);
        String md5password = MD5Util.MD5EncodeUtf8(user.getPassword());
        user.setPassword(md5password);
        setTemplateDateAndUser(user,request);//设置时间戳

        Random random = new Random();
        user.setUserFace(String.valueOf(random.nextInt(20)%(21))+".jpg");  //给用户一个随机头像
        int result = iUserService.register(user);
        if(result>0){
            return ServerResponse.createBySuccessMessage("注册成功");
        }
        return ServerResponse.createByErrorMessage("注册失败");
    }

    @RequestMapping(value = "logout.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> logout(HttpSession session) {
        session.removeAttribute(Const.CURRENT_USER);
        return ServerResponse.createBySuccess();
    }







    @RequestMapping(value = "forget_reset_password.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> forgetRestPassword(String username,String passwordNew,String forgetToken ){

        return iUserService.forgetRestPassWord(username,passwordNew,forgetToken);
    }



    @RequestMapping(value = "getUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<UserModel> get_information(Integer id){
        User user =iUserService.getUserInfo(id);
        if(user!=null){
            user.setPassword(null);//安全考虑，返回密码为空
            UserModel userModel = new AdminController().entityToModel(user);
            return ServerResponse.createBySuccess("成功获取用户信息",userModel);
        }

        return ServerResponse.createByErrorMessage("用户不存在");
    }


    //更换头像
    @RequestMapping("uploadface")
    @ResponseBody
    public ServerResponse upload(@RequestParam(value = "file",required = false) MultipartFile file, HttpServletRequest request, Integer id){


            User user = iUserService.selectUserById(id);
            if(user == null){
                return ServerResponse.createByErrorCodeMessage(Const.USER_IS_NO_EXIT,"用户不存在");
            }
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = fileService.uploadFace(file,path,Const.IMG_USERFACE);

            if(targetFileName ==null){
                return ServerResponse.createByErrorCodeMessage(Const.UPLOAD_FIED,"图片上传失败");
            }
            user.setUserFace(targetFileName);
            setTemplateDateAndUser(user,request);
            if(iUserService.updateByPrimaryKey(user)){
                return ServerResponse.createBySuccessMessage("头像更新成功");
            }
            return ServerResponse.createByErrorMessage("头像更新失败");

    }

    //更新信息
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<UserModel> update(@RequestBody UserModel userModel,HttpServletRequest request){
        User user =new AdminController().modelToEntity(userModel);
        setTemplateDateAndUser(user,request);
        if(iUserService.updateByPrimaryKey(user)){
            return ServerResponse.createBySuccess("个人信息更新成功!",userModel);
        }
        return ServerResponse.createByErrorMessage("操作失败,请重试!");
    }
    @RequestMapping(value = "selectJoinSportPerson", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse selectJoinSportPerson(Integer sportId){
        List<User> userList = iUserService.selectJoinSportPerson(sportId);
        if (userList!=null&& userList.size()>0){
            List<UserModel> userModelList = new ArrayList<>();
            for (User user:userList) {
                UserModel userModel = new AdminController().entityToModel(user);
                userModelList.add(userModel);
            }
            return ServerResponse.createBySuccess("查询成功",userModelList);
        }
        return ServerResponse.createBySuccess("无列表信息",null);
    }
    @RequestMapping(value = "addContactPerson", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse addContactPerson(Integer userId,Integer toUserId){

        if(iUserService.selectContactPerson(userId,toUserId)){
            return ServerResponse.createByErrorCodeMessage(Const.ALREADY_ADD_CONTACT_PERSON,"您已添加此用户作为联系人");
        }
        if(iUserService.insertContactPerson(userId,toUserId)){
            return ServerResponse.createBySuccessMessage("添加联系人成功");
        }
        return ServerResponse.createByErrorMessage("添加联系人失败");
    }
    @RequestMapping(value = "deleteContactPerson", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse deleteContactPerson(Integer userId,Integer toUserId){
        if(iUserService.deleteContactPerson(userId,toUserId)){
            return ServerResponse.createBySuccessMessage("删除联系人成功");
        }
        return ServerResponse.createByErrorMessage("删除联系人失败");
    }

    @RequestMapping(value = "selectContactPersons", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse selectContactPersons(Integer userId){
            List <User> userList =iUserService.selectContactPersonList(userId);
            if(userList!=null && userList.size()>0){
                List<UserModel> userModelList = new ArrayList<>();
                for (User user:userList) {
                    UserModel userModel = new AdminController().entityToModel(user);
                    userModelList.add(userModel);
                }
                return ServerResponse.createBySuccess("成功获取联系人",userModelList);
            }
        return ServerResponse.createByErrorMessage("暂无联系人");
    }
    @RequestMapping(value = "selectUserByPhone", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse selectUserByPhone(String phone){
        User user = iUserService.selectUserByPhone(phone);
        if(user!=null){
            UserModel userModel = new AdminController().entityToModel(user);
            return ServerResponse.createBySuccess("查询成功",userModel);
        }
        return ServerResponse.createByErrorMessage("用户不存在");
    }

    /**
     * 统一设置 Date 和 修改用户
     *
     * @param entity
     */
    public void setTemplateDateAndUser(User entity, HttpServletRequest request) {

        if (entity == null) {
            logger.error("ERR:Date set error.");
            return;
        }
        if (entity.getId() == null && entity.getCreateTime() == null) {
            //如果id为空， 就是新建
            entity.setCreateTime(new Date());
            entity.setCreateBy(entity.getNickname());
        } else {

            if (entity.getUpdateTime() == null) {
                entity.setUpdateTime(new Date());
            }
            if (entity.getUpdateBy() == null ) {
                entity.setUpdateBy(entity.getNickname());
            }
        }
    }



    /**
     * 获取客服机ip
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}